<template>
	<view class="uni-column">
		<view class="content" id="content" :style="{height:style.contentViewHeight+'px'}">
			<scroll-view id="scrollview" scroll-y="true" :style="{height:style.contentViewHeight+'px'}" :scroll-with-animation="true"
			    :scroll-top="scrollTop" @scrolltoupper="loadMoreHistory()" >
				<page-foot :name="fromNickName"></page-foot>
				<message-show v-for="(message,index) in chatRecords" :key="index" :message="message" :id="index" :baseUrl="baseUrl"></message-show>
				<view id="bottom"></view>
			</scroll-view>
		</view>
		<view class="foot">
			<chat-input @send-message="getInputMessage" @focus="inputGetFocus"></chat-input>
		</view>
	</view>
</template>

<script>
	import chatInput from '@/components/im/chatinput.vue';
	import messageShow from '@/components/im/messageshow.vue';
	import {chat} from '@/api/mcenter/index';
	const qiniuUploader = require("../../common/qiniuUploader");
	import { mapState,mapMutations,mapGetters } from 'vuex'
	import {
		getUrl
	} from '@/common/oss';
	import { getBasicUrl } from '@/common/env.config'

	export default {
		data() {
			return {
				baseUrl: "",
				page: 1,
				pageSize: 20,
				sendCount: 0,
				fromPartyId: "",
				messages: [],
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				scrollTop: 0,
				imageUrls: []
			}
		},
		components: {
			chatInput,
			messageShow
		},
		onUnload: function() {
			
		},
		onLoad: function (e) {
			const res = uni.getSystemInfoSync();
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100); //像素
			this.name = e.fromNickName;
			this.fromPartyId = e.fromPartyId
			this.baseUrl = getUrl();
			this.fromPartyId = e.fromPartyId;
			
		},
		computed:{
			...mapGetters(
				["userId",'sendedCount']
			),
			...mapState({
				userInfo: state => state.user.userInfo
			}),
			chatRecords () {
			  // 获取历史聊天记录
			  this.$nextTick(function () {
				this.scrollToBottom()
			  })
			  var items = this.$store.getters.getChatRecordById(this.fromPartyId);
			  if(items !== undefined && items.length > 0) {
				  var that = this;
				  items.forEach(p => {
				  	if(p.msgType == "IMAGE")
				  	{
						that.imageUrls.push(this.baseUrl+ p.content);
				  	}
				  });
			  }
			  
			  return this.$store.getters.getChatRecordById(this.fromPartyId)
			}
		},
		mounted() {
			this.$nextTick(function(){
				this.scrollToBottom();
			})
			this.sendCount = this.userInfo.DaylyMessageLimit;
			if(this.userInfo.vipTypeId !== undefined && this.userInfo.vipType.length > 0) {
				for(var i = 0; i < this.userInfo.benefitTypes.length; i++)
				{
					if(this.userInfo.benefitTypes[i].parentTypeId.equals("MESSAGE_COUNT"))
						this.sendCount = this.sendCount + this.userInfo.benefitTypes[i].benefitValue;
				}
				
			}
		},
		onBackPress: function(e) {
			this.$store.dispatch("clearUnreadCount", this.fromPartyId)
		},
		methods: {
			...mapMutations(['SET_FRIENDS','UPDATE_SENDED_MSG_COUNT']),
			setTitle: function(title) {
				uni.setNavigationBarTitle({
					title:title
				})
			},
			getInputMessage: function (message) {//获取子组件的输入数据
				if(this.sendedCount < this.sendCount)
				{
					this.addMessage('customer', message, false);
				} else {
					uni.showModal({
						title:"提示",
						content:"您的小纸条数量不够了，请自行购买，谢谢"
					})
				}
				
				
			},
			addMessage: function (user, meessage, msgType) {
				var that = this;
				let date = new Date()
				if(message.type == 'TEXT')
				{
					this.sendText(message)
				}
				else if(message.type == 'IMAGE') {
					
				}
			},
			sendText(message) {
				chat({
					content: meessage.content,
					msgType: meessage.type,
					createdStamp: new Date(),
					fromPartyId: this.userId,
					toPartyId: this.fromPartyId
				}).then(response => {
					if(response.status == 200 && response.rel == true) {
						response.data.user = user;
						this.SET_FRIENDS( {
							friendId: this.fromPartyId,
							chatRecord: response.data
						});
						this.UPDATE_SENDED_MSG_COUNT((this.sendedCount+1))
						this.toRobot(message.content)
						this.scrollToBottom();
					} else {
						uni.showModal({
							title:"提示",
							content:"没有发送成功，请重新发送"
						})
					}
				}).catch(error => {
					uni.showModal({
						title:"提示",
						content:"没有发送成功，请重新发送"
					})
				});
			},
			uploadImage(message) {
				//多张图片地址，保存到一个数组当中
				var msgs = [];
				var that = this;
				var state = 0;//state记录当前已经上传到第几张图片
				for (var i = 0; i < message.content.length; i++) {
					if(this.sendedCount < this.sendCount)
					{
						console.log("image.." +list[i])
						qiniuUploader.upload(message.content[i], (res) => {
							add({
								content: res.key,
								msgType: meessage.type,
								createdStamp: new Date(),
								fromPartyId: this.userId,
								toPartyId: this.fromPartyId
							}).then(response => {
									if(response.status == 200 && response.rel == true) {
										response.data.user = user;
										this.SET_FRIENDS( {
											friendId: this.fromPartyId,
											chatRecord: response.data
										});
										this.UPDATE_SENDED_MSG_COUNT((this.sendedCount+1))
										this.toRobot(message)
										this.scrollToBottom();
									} else {
										uni.showModal({
											title:"提示",
											content:"没有发送成功，请重新发送"
										})
									}
								}).catch(error => {
									uni.showModal({
										title:"提示",
										content:"没有发送成功，请重新发送"
									})
								});;
						}, (error) => {
							reject('error');
							console.log('error: ' + error);
						}, {
								region: 'SCN', // 华北区
								uptokenURL: getBasicUrl()+"/api/tool/oss/token?expires="+3600,
								domain: 'p6urwinfd.bkt.clouddn.com',
								shouldUseQiniuFileName: true
							})
					} else {
						uni.showModal({
							title:"提示",
							content:"你已经超过了小纸条的数量，如有需要，请另行购买"
						})
						break;
					}
					
				}
					
			},
			previewImage: function(e) {
				uni.previewImage({
					current: (this.baseUrl+e),
					urls: this.imageUrls
				});
			},
			scrollToBottom: function () {
				var that = this;
				var query = uni.createSelectorQuery();
				query.selectAll('.m-item').boundingClientRect();
				query.select('#scrollview').boundingClientRect();

				query.exec(function (res) {
					that.style.mitemHeight = 0;
					res[0].forEach(function (rect) {
						// console.info(rect.height);
						that.style.mitemHeight = that.style.mitemHeight + rect.height + 20;
					});

					if (that.style.mitemHeight > that.style.contentViewHeight) {
						that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight;
					}
				});
			},
			loadMoreHistory() {
				let query= {
					fromPartyId: this.fromPartyId,
					toPartyId: this.userId,
					page: this.page,
					limit: this.pageSize,
				}
				
				this.$store.dispatch("getFriendHistoryRecords", query).then(response => {
					this.page++
				}).catch(error => {
							uni.showModal({
								title:"提示",
								content:"服务器繁忙，请稍后再试试"
							})
						})
			}
		},
		
		
	}
</script>

<style>
	.uni-column {
		display: flex;
		flex-direction: column;
	}

	.content {

		display: flex;
		flex: 1;
		margin-bottom: 100upx;
	}

	.foot {
		position: fixed;
		width: 100%;
		height: 90upx;
		min-height: 90upx;
		left: 0upx;
		bottom: 0upx;
		overflow: hidden;
	}
</style>
